package com.ruoyi.common.h1wUtils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.Base64;
import com.qiniu.util.UrlSafeBase64;
import okhttp3.ResponseBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import okhttp3.RequestBody;
import javax.annotation.PostConstruct;
import java.awt.image.BufferedImage;
import java.io.*;

@Component
public class QiniuUtils {

    private static final Logger log = LoggerFactory.getLogger(QiniuUtils.class);

    @Value("${qiniu.accessKey}")
    private  String accessKey ;
    @Value("${qiniu.secretKey}")
    private  String secretKey ;
    @Value("${qiniu.bucket}")
    private  String bucket ;
    @Value("${qiniu.prefix}")
    private  String qiniuPrefix ;

    private  Auth auth;
    // 创建上传对象
    private  UploadManager uploadManager;

    @PostConstruct
    public void init(){
        auth = Auth.create(accessKey, secretKey);
        Configuration c = new Configuration(Region.autoRegion());
        uploadManager = new UploadManager(c);
    }

    /**
     * 获取七牛upToken
     */
    public  String getUpToken(){
        return auth.uploadToken(bucket);
    }

    /**
     * 获取七牛前缀
     */
    public String getQiniuPrefix(){
        return qiniuPrefix;
    }

    /**
     * 文本转二维码传到七牛
     */
    public  String uploadQrCode(String content) throws Exception {

        try {
            BufferedImage bufferedImage = QRCodeUtil.codeCreateBufferImage(content, 150, 150);
            if (bufferedImage != null) {
                InputStream inputStream = QRCodeUtil.bufferedImageToInputStream(bufferedImage);
                if (inputStream!=null){
                    //调用put方法上传
                    Response res = uploadManager.put(inputStream, null, getUpToken(),null,null);
                    if (res.isOK()){
                        DefaultPutRet putRet = new Gson().fromJson(res.bodyString(), DefaultPutRet.class);
                        return putRet.key;
                    }else{
                        log.error("上传失败"+res.error );
                        throw new Exception("上传失败");
                    }
                }else{
                    log.error("邀请码流转换异常" );
                    throw new Exception("邀请码流转换异常");
                }

            } else {
                log.error("生成邀请二维码异常" );
                throw new Exception("邀请码流转换异常");
            }

        } catch (QiniuException e) {
            // 请求失败时打印的异常的信息
            Response r = e.response;
            log.error("七牛异常:" + r.toString());
            throw new Exception("七牛异常");
        }
    }

    //上传
    //base64方式上传
    public String put64image(byte[] base64, String key) throws Exception{
        String file64 = Base64.encodeToString(base64, 0);
        Integer l = base64.length;
        String url = "http://upload.qiniu.com/putb64/" + l + "/key/"+ UrlSafeBase64.encodeToString(key);
        //非华东空间需要根据注意事项 1 修改上传域名
        RequestBody rb = RequestBody.create(null, file64);
        Request request = new Request.Builder().
                url(url).
                addHeader("Content-Type", "application/octet-stream")
                .addHeader("Authorization", "UpToken " + getUpToken())
                .post(rb).build();
        //System.out.println(request.headers());
        OkHttpClient client = new OkHttpClient();
        okhttp3.Response response = client.newCall(request).execute();
        //如果不需要添加图片样式，使用以下方式
        return qiniuPrefix + key;
    }

    //下载路径
    public String getDownloadUrl(String targetUrl) {
        return auth.privateDownloadUrl(targetUrl);
    }

    /**
     * 文件下载
     *
     * @param targetUrl
     */
    public String download(String targetUrl) {
        //获取downloadUrl
        String downloadUrl = getDownloadUrl(targetUrl);
        //本地保存路径
//        String filePath = "E:\\chen\\";
        String filePath = "/home/";
        return download(downloadUrl, filePath);
    }

    /**
     * 通过发送http get 请求获取文件资源
     * @param url
     * @param filepath
     */
    private static String download(String url, String filepath) {
        OkHttpClient client = new OkHttpClient();
        Request req = new Request.Builder().url(url).build();
        okhttp3.Response resp = null;
        try {
            resp = client.newCall(req).execute();
            System.out.println(resp.isSuccessful());
            if (resp.isSuccessful()) {
                ResponseBody body = resp.body();
                InputStream is = body.byteStream();
                byte[] data = readInputStream(is);
                //判断文件夹是否存在，不存在则创建
                File file = new File(filepath);
                if (!file.exists() && !file.isDirectory()) {
                    System.out.println("===文件夹不存在===创建====");
                    file.mkdir();
                }
                String imgName = "woodImg.jpg";
                File imgFile = new File(filepath + imgName);
                FileOutputStream fops = new FileOutputStream(imgFile);
                fops.write(data);
                fops.close();
                return filepath+imgName;
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Unexpected code " + resp);
        }
        return "";
    }

    /**
     * 读取字节输入流内容
     *
     * @param is
     * @return
     */
    private static byte[] readInputStream(InputStream is) {
        ByteArrayOutputStream writer = new ByteArrayOutputStream();
        byte[] buff = new byte[1024 * 2];
        int len = 0;
        try {
            while ((len = is.read(buff)) != -1) {
                writer.write(buff, 0, len);
            }
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return writer.toByteArray();
    }

}
